/*
Copyright 2014 Yury Kharlamov

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated Inversion-Of-Control container
https://code.google.com/p/gen-ioc/

* * *

Object Manager implementation
*/
#include "stdafx.h"
#include "GenIOC/ObjectManager.h"
#include "helpers.h"
#include "GenIOC/ShutdownManager.h"
#include "GenIOC/EventDispatcher.h"
#include "GenIOC/EventSourceBase.h"

class ObjectManager : public IObjectManager, public IEventQueue
{
private:
	struct ClassEntry
	{
		ClassEntry(const Factory& factory, const IfaceId& classId, const IfaceIdList& consumes, const IfaceIdList& emits, bool isSingleton)
		:factory(factory), classId(classId), consumes(consumes), emits(emits), isSingleton(isSingleton){}
		Factory factory;
		IfaceIdList consumes, emits;
		IfaceId classId;
		std::shared_ptr<IObject> object;
		bool isSingleton;
	};
	typedef boost::lock_guard<boost::mutex> LockGuard;
public:
	ObjectManager() : m_wasShutdownFinished(false)
	{
		IfaceIdList consumes;
		consumes.push_back(ID_OF(IEventDispatcher));
		IfaceIdList emits;
		emits.push_back(ID_OF(IObjectManager));
		AddFactory([]{return CreateEmbeddedObjectManager(); }, "ObjectManager", consumes, emits, false);
		//printf("ObjectManager\n");
	}

	/*~ObjectManager()
	{
		printf("~ObjectManager\n");
	}*/

	void AddFactory(const Factory& factory, const IfaceId& classId, const IfaceIdList& consumes, const IfaceIdList& emits, bool isSingleton) override
	{
		LockGuard lock(m_createObjMutex);
		m_classEntries.push_back(ClassEntry(factory, classId, consumes, emits, isSingleton));
	}
	std::shared_ptr<IObject> CreateObjectByIfaceId(const IfaceId& ifaceId, std::weak_ptr<IEventQueue> subscriber) override
	{
		return CreateObject(ifaceId, subscriber, false);
	}
	std::shared_ptr<IObject> CreateObjectByClassId(const IfaceId& classId, std::weak_ptr<IEventQueue> subscriber) override
	{
		return CreateObject(classId, subscriber, true);
	}

	std::shared_ptr<IObject> CreateObject(const IfaceId& ifaceId, std::weak_ptr<IEventQueue> subscriber, const boost::logic::tribool& isClassId)
	{
		LockGuard lock(m_createObjMutex);
		if (m_wasShutdownFinished)
			throw std::logic_error("CreateObject called on destroyed obj man");
		ClassEntry& e = GetClassEntry(ifaceId, isClassId);
		if (!e.isSingleton || !e.object)
		{
			std::shared_ptr<IObject> o = e.factory();
			std::weak_ptr<IEventQueue> createdSubscriber = std::dynamic_pointer_cast<IEventQueue>(o);
			if (!e.consumes.empty())
			{
				std::shared_ptr<ISetters> setters
					= std::dynamic_pointer_cast<ISetters>(o);
				if (!setters)
					throw std::exception("No setters");
				SetFactories(setters, e.consumes, createdSubscriber);
			}

			std::shared_ptr<IEventSource> evtSrc
				= std::dynamic_pointer_cast<IEventSource>(o);
			if (evtSrc)
				evtSrc->Subscribe(subscriber);

			std::shared_ptr<IShutdown> shutdown =
				std::dynamic_pointer_cast<IShutdown>(o);
			if (shutdown && m_shutdownMan)
			{
				if (!evtSrc)
					throw std::logic_error("IEventSource not implemented");
				evtSrc->Subscribe(m_shutdownManEvtQueue);
				m_shutdownMan->AddShutdownObject(shutdown);
			}
			if (!e.isSingleton)
				return o;
			e.object = o;
		}
		return e.object;
	}
	static std::shared_ptr<IObjectManager> Create()
	{
		std::shared_ptr<ObjectManager> objMan = std::make_shared<ObjectManager>();
		objMan->Initialize(objMan);
		return objMan;
	}
	void PushEvent(const boost::any& event) override
	{
		if (event.type() == typeid(ShutdownFinished))
		{
			{
				m_classEntries.clear();
				m_shutdownMan.reset();
				m_self.reset();

				LockGuard lock(m_createObjMutex);
				m_wasShutdownFinished = true;
				m_shutdownCond.notify_all();
			}
		}
	}
	void Shutdown() override
	{
		m_shutdownMan->Shutdown();
	}
	void WaitShutdownFinished() override
	{
		{
			boost::unique_lock<boost::mutex> lock(m_createObjMutex);
			while (!m_wasShutdownFinished)
				m_shutdownCond.wait(lock);
		}
	}
protected:
	void Initialize(const std::shared_ptr<ObjectManager>& self)
	{
		m_self = self;
		AddShutdownManagerFactory(this);
		AddEventDispatcherFactory(this);
		m_shutdownMan = std::dynamic_pointer_cast<IShutdownManager>(
			CreateObjectByIfaceId(ID_OF(IShutdownManager), m_self));
		m_shutdownManEvtQueue = std::dynamic_pointer_cast<IEventQueue>(m_shutdownMan);
	}

	ClassEntry& GetClassEntry(const IfaceId& ifaceId, const boost::logic::tribool& isClassId)
	{
		for (auto it = m_classEntries.begin(); it != m_classEntries.end(); ++it)
		{
			bool checkClassId = isClassId || boost::logic::indeterminate(isClassId);
			bool checkIfaceId = !isClassId || boost::logic::indeterminate(isClassId);
			if ((checkClassId && it->classId == ifaceId) || (checkIfaceId && Contains(it->emits, ifaceId)))
				return *it;
		}
		std::string err("No class emits ");
		err.append(ifaceId);
		throw std::exception(err.c_str());
	}
	void SetFactories(std::shared_ptr<ISetters>& setters, const IfaceIdList& consumes, std::weak_ptr<IEventQueue> subscriber)
	{
		for each(const IfaceId& id in consumes)
		{
			std::shared_ptr<ObjectManager> objMan = m_self;
			setters->SetIfaceFactory(id,
				[objMan, id, subscriber]
			{
				return objMan->CreateObject(id, subscriber, boost::logic::indeterminate);
			}
			);
		}
	}

	std::shared_ptr<ObjectManager> m_self;
	std::list<ClassEntry> m_classEntries;
	boost::mutex m_createObjMutex;
	std::shared_ptr<IShutdownManager> m_shutdownMan;
	std::weak_ptr<IEventQueue> m_shutdownManEvtQueue;
	boost::condition_variable_any m_shutdownCond;
	bool m_wasShutdownFinished;
};

class EmbeddedObjectManager: public ObjectManager, public EventSource, public ISetters
{
public:
	void PushEvent(const boost::any& event) override
	{
		ObjectManager::PushEvent(event);
		if (event.type() == typeid(ShutdownFinished))
		{
			DispatchEvent(ShutdownFinished(this));
		}
	}
	static std::shared_ptr<IObjectManager> Create()
	{
		std::shared_ptr<EmbeddedObjectManager> objMan = std::make_shared<EmbeddedObjectManager>();
		objMan->Initialize(objMan);
		return objMan;
	}
	void SetIfaceFactory(const IfaceId& ifaceId, const Factory& factory) override
	{
		if (ifaceId == ID_OF(IEventDispatcher))
			SetDispatcherFactory(factory);
	}
};

std::shared_ptr<IObjectManager> CreateObjectManager()
{
	return ObjectManager::Create();
}


std::shared_ptr<IObjectManager> CreateEmbeddedObjectManager()
{
	return EmbeddedObjectManager::Create();
}